import React from 'react';
import PropTypes from 'prop-types';
import Dropdown from '@components/dropdown';
import { get } from 'lodash';
import cn from 'classnames';
import { message } from 'antd';
import rsa from '@util/rsa';
import { resetPassword, unlockUser, deleteUser } from '@api/user';
import './index.less';

const Operator = props => {
  const { row, afterReset, afterDelete, onEditUser } = props;
  const disabledEdit = get(row, 'isDefaultRole') && get(row, 'nickname') !== '安全管理员';
  const more = {
    title: '更多',
    menus: [
      {
        title: '重置密码',
        info: '是否要重置密码?',
        closeDropdownBeforeConfirm: true,
        onConfirm: () =>
          resetPassword({
            // eslint-disable-next-line
            user_id: row._id,
            publicKey: rsa.getKeys('local').public
          })
            .then(res => {
              const password = get(res, 'data.data.password', '');
              afterReset(rsa.decrypt(password, rsa.getKeys('local').private));
            })
            .catch(() => {
              message.error('重置密码失败');
            })
      },
      {
        title: '解锁',
        info: '是否要解锁用户?',
        onConfirm: () =>
          unlockUser(row._id)
            .then(() => {
              message.success('解锁用户成功');
            })
            .catch(() => {
              message.error('解锁用户失败');
            })
      },
      {
        title: '删除',
        info: '是否要删除用户?',
        disabled: get(row, 'isDefaultRole'),
        closeDropdownBeforeConfirm: true,
        className: 'delete',
        onConfirm: () =>
          deleteUser(row._id)
            .then(() => {
              message.success('删除用户成功');
              afterDelete();
            })
            .catch(() => {
              message.error('删除用户失败');
            })
      }
    ]
  };
  // const disabled = get(row, 'role_oid.is_admin');
  return (
    <div className="user-manage-table-operator">
      <span
        className={cn('edit', { disabledEdit }, 'be-color')}
        onClick={() => !disabledEdit && onEditUser()}
      >
        编辑
      </span>
      <Dropdown {...more} />
    </div>
  );
};

Operator.propTypes = {
  onEditUser: PropTypes.func,
  row: PropTypes.object,
  afterReset: PropTypes.func,
  afterDelete: PropTypes.func
};

export default Operator;
